/*
 * @lc app=leetcode.cn id=24 lang=cpp
 *
 * [24] 两两交换链表中的节点
 */

struct ListNode
{
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

// @lc code=start
class Solution
{
public:
    ListNode *swapPairs(ListNode *head)
    {
        if (head == nullptr || head->next == nullptr)
            return head;
        
        ListNode *p_odd = head;
        ListNode *p_even = head->next;
        ListNode *temp = nullptr;

        head = p_even;
        while (p_even != nullptr)
        {
            /* 两两交换 */
            temp = p_even->next;
            p_even->next = p_odd;
            if (temp != nullptr && temp->next != nullptr)
            {
                p_odd->next = temp->next;
                p_odd = temp;
                p_even = temp->next;
            }
            else if (temp != nullptr)
            {
                p_odd->next = temp;
                break;
            }
            else
            {
                p_odd->next = nullptr;
                break;
            }
        }
        
        return head;
    }
};
// @lc code=end
